package com.lwx.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwx.sys.constant.Constant;
import com.lwx.sys.domain.Permission;
import com.lwx.sys.mapper.PermissionMapper;
import com.lwx.sys.mapper.RoleMapper;
import com.lwx.sys.service.PermissionService;
import com.lwx.sys.utils.DataGridView;
import com.lwx.sys.utils.TreeNode;
import com.lwx.sys.vo.PermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwx
 * @since 2020-04-04
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Permission> queryAllPermissionForList(PermissionVo permissionVo) {
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        if (null!= permissionVo){
            //type ="menu"
            permissionQueryWrapper.eq(StringUtils.isNotBlank(permissionVo.getType()),"type",permissionVo.getType());
            //available = 1
            permissionQueryWrapper.eq(permissionVo.getAvailable()!=null,"available",permissionVo.getAvailable());

        }
        permissionQueryWrapper.orderByAsc("ordernum");
        //select * from sys_permission where type= "menu" and available = 1
        List<Permission> permissionList = permissionMapper.selectList(permissionQueryWrapper);
        return permissionList;
    }

    @Override
    public DataGridView loadAllPermission(PermissionVo permissionVo) {
        QueryWrapper<Permission> qw = new QueryWrapper<>();
//        qw.eq(permissionVo.getId() != null,"id",permissionVo.getId()).or().eq(permissionVo.getId()!=null,"pid",permissionVo.getId());
        qw.like(StringUtils.isNotBlank(permissionVo.getTitle()),"title",permissionVo.getTitle());
        qw.eq(StringUtils.isNotBlank(permissionVo.getType()),"type",permissionVo.getType());
        qw.eq(permissionVo.getAvailable()!= null,"available", Constant.AVAILABLE_TRUE);
        qw.eq(StringUtils.isNotBlank(permissionVo.getPercode()),"percode", permissionVo.getPercode());
        //        qw.like(StringUtils.isNotBlank(permissionVo.getAddress()),"address",permissionVo.getAddress());
//        qw.like(StringUtils.isNotBlank(permissionVo.getRemark()),"remark",permissionVo.getRemark());

        qw.and(permissionVo.getId() != null, new Consumer<QueryWrapper<Permission>>() {
            @Override
            public void accept(QueryWrapper<Permission> t) {
                t.eq(permissionVo.getId() != null,"id",permissionVo.getId()).or().eq(permissionVo.getId()!=null,"pid",permissionVo.getId());
            }
        });
        qw.orderByDesc("ordernum");
        //select * from sys_login where createtime like "?" and createtime> ? and createtime < ?

        //分页
        Page page = new Page<>(permissionVo.getPage(), permissionVo.getLimit());

        //查询数据库
        permissionMapper.selectPage(page,qw);

        return new DataGridView(page.getTotal(),page.getRecords());
    }

    //增删改都要加事务
    @Transactional
    @Override
    public void deletePermission(Integer id) {

        permissionMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void batchDeletePermission(Integer[] ids) {

        permissionMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Transactional
    @Override
    public void addPermission(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Transactional
    @Override
    public void updatePermission(Permission permission) {
        permissionMapper.updateById(permission);
    }

    @Override
    public Integer queryPermissionCountByPid(Integer id) {

        return permissionMapper.queryPermissionCountByPid(id);
    }

    @Override
    public Integer queryPermissionMaxOrderNum() {
        return permissionMapper.queryPermissionMaxOrderNum();
    }

    @Override
    public DataGridView queryRolePermissionByRoleId(Integer roleId) {

        QueryWrapper<Permission> qw = new QueryWrapper<>();
        qw.eq("available", Constant.AVAILABLE_TRUE);
        //1.查询所有可用的菜单和权限
        List<Permission> allPermission = permissionMapper.selectList(qw);
        //select * from sys_permission where abaileable=1;

        //2.根据角色Id查询当前角色拥有的权限集合
        List<Integer> permissionIds = permissionMapper.queryPermissionIdsByRoleId(roleId);
        //	select pid from sys_role_permission where rid=#{roleId}
        List<Permission> currentRolePermission = null;
        if (permissionIds == null || permissionIds.size() == 0) {
            currentRolePermission = new ArrayList<>();
        } else {
            qw.in("id", permissionIds);
            currentRolePermission = permissionMapper.selectList(qw);
            //select * from sys_permission where abaileable=1 and id in(18,21,22);
        }

        List<TreeNode> nodes = new ArrayList<>();
        for (Permission p1 : allPermission) {
            String checkArr = "0";
            for (Permission p2 : currentRolePermission) {
                if (p1.getId() == p2.getId()) {
                    checkArr = "1";
                    break;
                }
            }
            Boolean spread = p1.getOpen() == null ? false : p1.getOpen() == 1 ? true : false;
            TreeNode t1 = new TreeNode(p1.getId(), p1.getPid(), p1.getTitle(), spread, checkArr);
            nodes.add(t1);
        }
        return new DataGridView(nodes);
    }

    @Override
    public List<String> queryPermissionByUserId(Integer id) {
        //根据用户Id查询角色Id
        List<Integer> roleIds = roleMapper.selectRoleIdsByUserId(id);
        if (null == roleIds && roleIds.size() ==0){
            return null;
        }else {
            //根据角色id集合查询权限id
            List<Integer> permissionIds =permissionMapper.queryPermissionIdsByRoleIds(roleIds);

            if (null == permissionIds && permissionIds.size() == 0){
                return null;
            }else {
                QueryWrapper<Permission> qw = new QueryWrapper<>();
                qw.eq("available",Constant.AVAILABLE_TRUE);
                qw.eq("type",Constant.TYPE_PERMISSION);
                qw.in("id",permissionIds);
                //查询改用户所有权限
                List<Permission> permissions = this.permissionMapper.selectList(qw);

                List<String> pers = new ArrayList<>();
                for (Permission permission:permissions){
                    //获取权限名放入list
                    pers.add(permission.getPercode());
                }
                return pers;
            }
        }
    }

    @Override
    public List<Permission> queryPermissionByUserIdForlist(PermissionVo permissionVo, Integer id) {
        //根据用户id查询角色id
        this.roleMapper.selectRoleIdsByUserId(id);
        //根据用户Id查询角色Id
        List<Integer> roleIds = roleMapper.selectRoleIdsByUserId(id);
        if (null == roleIds && roleIds.size() ==0){
            return null;
        }else {
            //根据角色id集合查询权限id
            List<Integer> permissionIds =permissionMapper.queryPermissionIdsByRoleIds(roleIds);

            if (null == permissionIds && permissionIds.size() == 0){
                return null;
            }else {
                QueryWrapper<Permission> qw = new QueryWrapper<>();
                qw.eq("available",Constant.AVAILABLE_TRUE);
                qw.eq("type",Constant.TYPE_MENU);
                qw.in("id",permissionIds);
                //查询改用户所有权限

                List<Permission> permissions = this.permissionMapper.selectList(qw);
                return permissions;
            }
        }
    }
}
